package com.workshop.utils.session;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * session 管理
 * @author chenluqiang
 * @date 2019年4月16日 下午3:52:24 
 *
 */
public class SessionManager {
	private static SessionManager sessionManager = null;
	private static Map<String,HttpSession> sessionMap;
	
	private SessionManager () {
		sessionMap = new HashMap<String,HttpSession>();
	}
	
	public static SessionManager getInstance() {
		if(sessionManager==null) {
			sessionManager = new SessionManager();
		}
		return sessionManager;
	}
	
	public synchronized void addSession(HttpSession session) {  
        if (session != null) {  
            sessionMap.put(session.getId(), session);  
        }  
    }  

    public synchronized void delSession(HttpSession session) {  
        if (session != null) {  
            sessionMap.remove(session.getId());  
        }  
    }  

    public synchronized HttpSession getSession(String sessionID) {  
        if (sessionID == null) {  
            return null;  
        }  
        return sessionMap.get(sessionID);  
    }  
    
    public static String saveUserBySession(HttpServletRequest request,Object user) {
		HttpSession session = request.getSession();
		 //获取session的Id
        String sessionId = session.getId();
        //将数据存储到session中
        session.setAttribute("user",user);
        SessionManager sessionManager = getInstance();
        HttpSession httpSession = sessionManager.getSession(sessionId);
        if(httpSession==null) {
        	System.out.println("服务器不存在该session");
        	sessionManager.addSession(session);
        }
        //判断session是不是新创建的
        if (session.isNew()) {
            System.out.println("session创建成功，session的id是："+sessionId);
        }else {
        	System.out.println("服务器已经存在该session了，session的id是："+sessionId);
        }
		return sessionId;
	}
}
